﻿$(function () {
    document.body.className = localStorage.getItem('config-skin');
    $("[data-toggle='tooltip']").tooltip();
})

$.reload = function () {
    location.reload();
    return false;
}

$.loading = function (bool, text) {
    var $loadingpage = top.$("#loadingPage");
    var $loadingtext = $loadingpage.find('.loading-content');
    if (bool) {
        $loadingpage.show();
    } else {
        if ($loadingtext.attr('istableloading') == undefined) {
            $loadingpage.hide();
        }
    }
    $loadingtext.html("");
    $loadingtext.css("left", (top.$('body').width() - $loadingtext.width()) / 2 - 50);
    $loadingtext.css("top", (top.$('body').height() - $loadingtext.height()) / 2);
}

$.request = function (name) {
    var search = location.search.slice(1);
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == name) {
            if (decodeURI(ar[1]) == 'undefined') {
                return "";
            } else {
                return decodeURI(ar[1]);
            }
        }
    }
    return "";
}

$.currentWindow = function () {
    var iframeId = top.$(".Huikaoba_iframe:visible").attr("id");
    return top.frames[iframeId];
}

$.browser = function () {
    var userAgent = navigator.userAgent;
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera"
    };
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    }
    if (userAgent.indexOf("Chrome") > -1) {
        if (window.navigator.webkitPersistentStorage.toString().indexOf('DeprecatedStorageQuota') > -1) {
            return "Chrome";
        } else {
            return "360";
        }
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    }
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    };
}

$.download = function (url, data, method) {
    if (url && data) {
        data = typeof data == 'string' ? data : jQuery.param(data);
        var inputs = '';
        $.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        $('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
    };
};

$.modalOpen = function (options) {
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        shade: 0.3,
        myscrolling: true,
        btn: ['确认', '关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: null,
        cancel: function () {
            return true;
        }
    };
    var options = $.extend(defaults, options);
    var _width = top.$(window).width() > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px';
    var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px';

    //自定义参数，用来设置滚动条是否显示
    var content = options.url;
    if (!options.myscrolling) {
        content = [options.url, 'no'];
    }

    top.layer.open({
        id: options.id,
        type: 2,
        shade: options.shade,
        title: options.title,
        fix: false,
        area: [_width, _height],
        content: content,
        btn: options.btn,
        btnclass: options.btnclass,
        yes: function () {
            options.callBack(options.id);
        },
        cancel: options.cancel,
        success: function () {
            $.loading(false);
        }
    });
    $.loading(true);
}

//点击关闭执行父页面刷新
$.modalOpenRefresh = function (options) {
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        shade: 0.3,
        myscrolling: true,
        btn: ['关闭'],
        btnclass: ['btn btn-danger'],
        callBack: null,
        cancel: function () {
            return true;
        }
    };
    var options = $.extend(defaults, options);
    var _width = top.$(window).width() > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px';
    var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px';

    //自定义参数，用来设置滚动条是否显示
    var content = options.url;
    if (!options.myscrolling) {
        content = [options.url, 'no'];
    }

    top.layer.open({
        id: options.id,
        type: 2,
        shade: options.shade,
        title: options.title,
        fix: false,
        area: [_width, _height],
        content: content,
        btn: options.btn,
        btnclass: options.btnclass,
        yes: function () {
            options.callBack(options.id);
        },
        btn2: options.btn2,
        cancel: options.cancel,
        success: function () {
            $.loading(false);
        }
    });
    $.loading(true);
}

//开窗口只有关闭按钮 hafy 2017.10.20
$.modalOpenOnlyClose = function (options) {
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        shade: 0.3,
        myscrolling: true,
        btn: ['关闭'],
        btnclass: ['btn btn-danger'],
        callBack: null,
        cancel: function () {
            return true;
        }
    };
    var options = $.extend(defaults, options);
    var _width = top.$(window).width() > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px';
    var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px';

    //自定义参数，用来设置滚动条是否显示
    var content = options.url;
    if (!options.myscrolling) {
        content = [options.url, 'no'];
    }

    top.layer.open({
        id: options.id,
        type: 2,
        shade: options.shade,
        title: options.title,
        fix: false,
        area: [_width, _height],
        content: content,
        btn: options.btn,
        btnclass: options.btnclass,
        cancel: options.cancel,
        success: function () {
            $.loading(false);
        }
    });
    $.loading(true);
}

$.modalConfirm = function (content, callBack) {
    top.layer.confirm(content, {
        icon: "fa-exclamation-circle",
        title: "系统提示",
        btn: ['确认', '取消'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
    }, function (index) {
        callBack(true);
        top.layer.close(index);
    }, function () {
        callBack(false);
    });
}

//自定义询问弹窗 a-fei 时间：2016-11-04
$.myModalConfirm = function (options) {
    var defaults = {
        content: "",
        icon: "fa-exclamation-circle",
        title: "系统提示",
        btn: ['确认', '取消'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        yes: function () { },
        no: function () { },
    };
    var options = $.extend(defaults, options);
    top.layer.confirm(options.content, {
        icon: options.icon,
        title: options.title,
        btn: options.btn,
        btnclass: options.btnclass,
    }, function (index) {
        options.yes(true);
        top.layer.close(index);
    }, function () {
        options.no(false);
    });
}

$.modalAlert = function (content, type) {
    var icon = "";
    if (type == 'success') {
        icon = "fa-check-circle";
    }
    if (type == 'error') {
        icon = "fa-times-circle";
    }
    if (type == 'warning') {
        icon = "fa-exclamation-circle";
    }
    top.layer.alert(content, {
        icon: icon,
        title: "系统提示",
        btn: ['确认'],
        btnclass: ['btn btn-primary'],
    });
}

$.modalMsg = function (content, type) {
    if (type != undefined) {
        var icon = "";
        if (type == 'success') {
            icon = "fa-check-circle";
        }
        if (type == 'error') {
            icon = "fa-times-circle";
        }
        if (type == 'warning') {
            icon = "fa-exclamation-circle";
        }
        top.layer.msg(content, { icon: icon, time: 4000, shift: 5 });
        top.$(".layui-layer-msg").find('i.' + icon).parents('.layui-layer-msg').addClass('layui-layer-msg-' + type);
    } else {
        top.layer.msg(content);
    }
}

$.modalClose = function () {
    var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    var $IsdialogClose = top.$("#layui-layer" + index).find('.layui-layer-btn').find("#IsdialogClose");
    var IsClose = $IsdialogClose.is(":checked");
    if ($IsdialogClose.length == 0) {
        IsClose = true;
    }
    if (IsClose) {
        top.layer.close(index);
    } else {
        location.reload();
    }
}

$.submitForm = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true,
        showMessage: true,
    };
    var options = $.extend(defaults, options);
    $.loading(true, options.loading);
    window.setTimeout(function () {
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.state == "success") {
                    options.success(data);
                    if (options.showMessage) {
                        $.modalMsg(data.message, data.state);
                    }
                    if (options.close == true) {
                        $.modalClose();
                    }
                } else {
                    $.modalAlert(data.message, data.state);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function () {
                $.loading(true, options.loading);
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}

$.submitFormWithError = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true,
        showMessage: true,
    };
    var options = $.extend(defaults, options);
    $.loading(true, options.loading);
    window.setTimeout(function () {
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.state == "success") {
                    options.success(data);
                    if (options.showMessage) {
                        $.modalMsg(data.message, data.state);
                    }
                    if (options.close == true) {
                        $.modalClose();
                    }
                } else {
                    $.modalAlert(data.message, data.state);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function () {
                $.loading(true, options.loading);
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}

$.deleteForm = function (options) {
    var defaults = {
        prompt: "注：您确定要删除该项数据吗？",
        url: "",
        param: [],
        loading: "正在删除数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    if ($('[name=__RequestVerificationToken]').length > 0) {
        options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    $.modalConfirm(options.prompt, function (r) {
        if (r) {
            $.loading(true, options.loading);
            window.setTimeout(function () {
                $.ajax({
                    url: options.url,
                    data: options.param,
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            options.success(data);
                            $.modalMsg(data.message, data.state);
                        } else {
                            $.modalAlert(data.message, data.state);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.loading(false);
                        $.modalMsg(errorThrown, "error");
                    },
                    beforeSend: function () {
                        $.loading(true, options.loading);
                    },
                    complete: function () {
                        $.loading(false);
                    }
                });
            }, 500);
        }
    });

}

$.jsonWhere = function (data, action) {
    if (action == null) return;
    var reval = new Array();
    $(data).each(function (i, v) {
        if (action(v)) {
            reval.push(v);
        }
    })
    return reval;
}

$.fn.jqGridRowValue = function () {
    var $grid = $(this);
    var selectedRowIds = $grid.jqGrid("getGridParam", "selarrrow");
    var json = [];
    var rowData;
    if (selectedRowIds != "") {
        var len = selectedRowIds.length;
        for (var i = 0; i < len ; i++) {
            rowData = $grid.jqGrid('getRowData', selectedRowIds[i]);
            json.push(rowData);
        }
    } else {
        if (!!$grid.jqGrid('getGridParam', 'selrow')) {
            rowData = $grid.jqGrid('getRowData', $grid.jqGrid('getGridParam', 'selrow'));
            json.push(rowData);
        }
    };
    return json;
}

$.fn.formValid = function () {
    return $(this).valid({
        errorPlacement: function (error, element) {
            element.parents('.formValue').addClass('has-error');
            element.parents('.has-error').find('i.error').remove();
            element.parents('.has-error').append('<i class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
            $("[data-toggle='tooltip']").tooltip();
            if (element.parents('.input-group').hasClass('input-group')) {
                element.parents('.has-error').find('i.error').css('right', '33px')
            }
        },
        success: function (element) {
            element.parents('.has-error').find('i.error').remove();
            element.parent().removeClass('has-error');
        }
    });
}

//自己可扩展的一个验证方法a-fei时间：2016-10-25
$.fn.myFormValid = function (options) {
    var defaults = {
        errorPlacement: function (error, element) {
            element.parents('.formValue').addClass('has-error');
            element.parents('.has-error').find('i.error').remove();
            element.parents('.has-error').append('<i class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
            $("[data-toggle='tooltip']").tooltip();
            if (element.parents('.input-group').hasClass('input-group')) {
                element.parents('.has-error').find('i.error').css('right', '33px')
            }
        },
        success: function (element) {
            element.parents('.has-error').find('i.error').remove();
            element.parent().removeClass('has-error');
        },
        rules: {},
        messages: {},
    };
    var options = $.extend(defaults, options);
    return $(this).valid({
        errorPlacement: options.errorPlacement,
        success: options.success,
        rules: options.rules,
        messages: options.messages,
    }
    );
}

//自己扩展的特殊格式时间（Y-m-dTH:i:s.fff）格式化方法 a-fei时间：2016-11-03
$.myTimeFormat = function (para) {
    if (para == null) {
        return "----";
    } else {
        var sendTime = para.replace('T', '');
        var timeYmd = sendTime.substr(0, 10);
        var timeHms = sendTime.substr(10, 8);
        return timeYmd + " " + timeHms;
    }
}

$.fn.formSerialize = function (formdate) {
    var element = $(this);
    if (!!formdate) {
        for (var key in formdate) {
            var $id = element.find('#' + key);
            var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            if ($id.hasClass("select2-hidden-accessible")) {
                type = "select";
            }
            switch (type) {
                case "checkbox":
                    if (value == "true") {
                        $id.attr("checked", 'checked');
                    } else {
                        $id.removeAttr("checked");
                    }
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    break;
                default:
                    $id.val(value);
                    break;
            }
        };
        return false;
    }
    var postdata = {};
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var id = $this.attr('id');
        var type = $this.attr('type');
        switch (type) {
            case "checkbox":
                postdata[id] = $this.is(":checked");
                break;
            default:
                var value = $this.val() == "" ? "&nbsp;" : $this.val();
                if (!$.request("keyValue")) {
                    if (value != null) {
                        value = value.replace(/&nbsp;/g, '');
                    }
                }
                postdata[id] = value;
                break;
        }
    });
    if ($('[name=__RequestVerificationToken]').length > 0) {
        postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    return postdata;
};

//自己扩展的form提交数据收集
$.fn.myFormSerialize = function (formdate) {
    var element = $(this);
    if (!!formdate) {
        for (var key in formdate) {
            var $id = element.find('#' + key);
            var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            if ($id.hasClass("select2-hidden-accessible")) {
                type = "select";
            }
            switch (type) {
                case "checkbox":
                    if (value == "true") {
                        $id.attr("checked", 'checked');
                    } else {
                        $id.removeAttr("checked");
                    }
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    break;
                default:
                    $id.val(value);
                    break;
            }
        };
        return false;
    }
    var postdata = {};
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var id = $this.attr('id');
        var type = $this.attr('type');
        switch (type) {
            case "checkbox":
                var name = $this.attr('name');
                if ($this.is(":checked")) {
                    if (!!postdata[name] || postdata[name] === false) {
                        if (!!postdata[name + "checkboxNum"]) {
                            postdata[name] = $this.val();
                            postdata[name + "checkboxNum"] = null;
                        } else {
                            postdata[name] = postdata[name] + ',' + $this.val();
                        }
                    } else {
                        postdata[name] = $this.val();
                    }
                } else {
                    if (!!postdata[name] || postdata[name] === false) {
                        if (!!postdata[name + "checkboxNum"]) {
                            postdata[name] = null;
                        }
                    } else {
                        postdata[name] = false;
                        postdata[name + "checkboxNum"] = 1;
                    }
                }
                break;
            case "radio":
                var name = $this.attr('name');
                var str = "input[name='" + name + "']:checked";
                postdata[name] = $(str).val();
                break;
            default:
                var value = ($this.val() == "" || $this.val() == undefined || $this.val() == null) ? "&nbsp;" : $this.val();
                if (!$.request("keyValue")) {
                    value = value.replace(/&nbsp;/g, '');
                }
                postdata[id] = value;
                break;
        }
    });
    if ($('[name=__RequestVerificationToken]').length > 0) {
        postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    return postdata;
};

$.fn.bindSelect = function (options) {
    var defaults = {
        id: "id",
        text: "text",
        search: false,
        url: "",
        param: [],
        change: null
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    if (options.url != "") {
        $.ajax({
            url: options.url,
            data: options.param,
            dataType: "json",
            async: false,
            success: function (data) {
                $.each(data, function (i) {
                    $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]));
                });
                $element.select2({
                    minimumResultsForSearch: options.search == true ? 0 : -1
                });
                $element.on("change", function (e) {
                    if (options.change != null) {
                        options.change(data[$(this).find("option:selected").index()]);
                    }
                    $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                });
            }
        });
    } else {
        $element.select2({
            minimumResultsForSearch: -1
        });
    }
}

$.fn.authorizeButton = function () {
    var moduleId = top.$(".Huikaoba_iframe:visible").attr("id").substr(6);
    var dataJson = top.clients.authorizeButton[moduleId];
    var $element = $(this);
    $element.find("*[authorize=yes]").attr("authorize", "no");
    if (dataJson != undefined) {
        $.each(dataJson, function (i) {
            if (dataJson[i].EnCode != null) {
                $element.find("#" + dataJson[i].EnCode).attr("authorize", "yes");
                //如果是Tab标签，需要将其内容页的authorize属性置为yes
                $element.find("[parentid = " + dataJson[i].EnCode + "]").attr("authorize", "yes");
            }
        });
    }
    $element.find("[authorize=no]").parents("li").prev(".split").remove();
    $element.find("[authorize=no]").parents("li").remove();
    $element.find("[authorize=no]").remove();
}

//原生Tab权限控制
$.fn.authorizeForNativeTab = function () {
    var moduleId = top.$(".Huikaoba_iframe:visible").attr("id").substr(6);
    var dataJson = top.clients.authorizeButton[moduleId];
    var $element = $(this);
    $element.find("*[authorize=yes]").attr("authorize", "no");
    if (dataJson != undefined) {
        $.each(dataJson, function (i) {
            if (dataJson[i].EnCode != null) {
                $element.find("#" + dataJson[i].EnCode.trim()).attr("authorize", "yes");
                //如果是Tab标签，需要将其内容页的authorize属性置为yes
                $element.find("[parentid = " + dataJson[i].EnCode.trim() + "]").attr("authorize", "yes");
            }
        });
    }
    $element.find("[authorize=no]").parents("li").prev(".split").remove();
    $element.find("[authorize=no]").parents("li").remove();
    $element.find("[authorize=no]").remove();
}

//Tab标签的权限控制 2017-10-24 silence
$.fn.authorizeForLayuiTab = function () {
    //找到Iframe页面对应的菜单Id
    var moduleId = top.$(".Huikaoba_iframe:visible").attr("id").substr(6);
    //获取具有权限的标签页数据
    var dataJson = top.clients.authorizeButton[moduleId];
    //找到对应的DOM元素，$(this)在此处表示$(.layui-tab)
    var $element = $(this);
    //首先将有权限控制功能的li标签的authorize属性的值设置为no
    $element.find("li[authorize=yes]").attr("authorize", "no");
    //如果请求的权限JSON数据存在，将其authorize属性置为yes
    if (dataJson != undefined) {
        $.each(dataJson,
            function (i) {
                $element.find("#" + dataJson[i].EnCode).attr("authorize", "yes");
            });
    }
    //获得本标签的lay-filter属性值
    var filter = $element.attr("lay-filter");
    layui.use(["element"], function () {
        var tabElement = layui.element;
        $element.find("li[authorize=no]").each(function () {
            //filter表示过滤属性，是lay-filter的值，让控件知道监听哪个Tab
            //$(this).attr("lay-id")是删除标签时的Id
            tabElement.tabDelete(filter, $(this).attr("lay-id"));
        });
        //将包含Tab标签的DIV展示出来
        $element.show();
    });
};

//根据权限和自定义属性控制可变按钮的是否可见 2017.6.1 hafy
$.fn.authorizeButtonForUnstable = function () {
    var moduleId = top.$(".Huikaoba_iframe:visible").attr("id").substr(6);
    var dataJson = top.clients.authorizeButton[moduleId];
    var $element = $(this);
    $element.find('[authorize=yes]').attr('authorize', 'no');
    if (dataJson != undefined) {
        $.each(dataJson, function (i) {
            $element.find("[specialFundation=" + dataJson[i].EnCode + "]").attr('authorize', 'yes');
        });
    }
    $element.find("[authorize=no]").parents('li').prev('.split').remove();
    $element.find("[authorize=no]").parents('li').remove();
    $element.find('[authorize=no]').remove();
}

$.fn.dataGrid = function (options) {
    var defaults = {
        datatype: "json",
        autowidth: true,
        rownumbers: true,
        shrinkToFit: false,
        gridview: true,
        //自定义属性，标识是否展示编辑删除等操作菜单
        isShowOperate: true
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    options["onSelectRow"] = function (rowid) {
        var rowData = $(this).jqGridRowValue();
        var length = rowData.length;
        if (!options.isShowOperate) {
            return false;
        }
        var $operate = $(".operate");
        if (length > 0) {
            $operate.animate({ "left": 0 }, 200);
            if (!!$(".mySelectedCount")) {
                $(".mySelectedCount").text(length);
            }
        } else {
            $operate.animate({ "left": '-100.1%' }, 200);
        }
        $operate.find('.close').click(function () {
            $operate.animate({ "left": '-100.1%' }, 200);
        });
    };
    options["onSelectAll"] = function (rowid) {
        var rowData = $(this).jqGridRowValue();
        var length = rowData.length;
        //如果配置为不显示，则直接返回false
        if (!options.isShowOperate) {
            return false;
        }
        var $operate = $(".operate");
        if (length > 0) {
            $operate.animate({ "left": 0 }, 200);
            if (!!$(".mySelectedCount")) {
                $(".mySelectedCount").text(length);
            }
        } else {
            $operate.animate({ "left": '-100.1%' }, 200);
        }
        $operate.find('.close').click(function () {
            $operate.animate({ "left": '-100.1%' }, 200);
        });
    };
    $element.jqGrid(options);
};

//自定义加载表单（后台获取JSON数据放入Form表单中，Name为唯一区别）
$.fn.loadDataForForm = function (url, param) {
    //url为请求数据的URL，param为请求数据要传递的参数
    //采用post方法请求数据，之后还会再扩充
    var obj = $(this);
    //请求数据
    $.ajax({
        type: "post",
        data: param,
        url: url,
        beforeSend: function () {
            $.loading(true);
        },
        success: function (data) {
            try {
                //将请求到的数据格式化为JSON
                data = JSON.parse(data);
                $.each(data[0],
                    function (key, value) {
                        //填充input输入框，找到name与json键相同的控件
                        var $oinput = obj.find("input[name='" + key + "']");
                        var $img = obj.find("img[id='" + key + "']");
                        //判断input类型
                        if ($oinput.attr("type") == "radio" || $oinput.attr("type") == "checkbox") {
                            //循环赋值
                            $oinput.each(function () {
                                //是复选框，并且是数组 
                                if (Object.prototype.toString.apply(value) == "[object Array]") {
                                    for (var i = 0; i < value.length; i++) {
                                        if ($(this).val() == value[i])
                                            $(this).attr("checked", "checked");
                                    }
                                } else {
                                    if ($(this).val() == value)
                                        $(this).attr("checked", "checked");
                                }
                            });
                        } else if ($oinput.attr("type") == "textarea") {
                            //多行文本框 
                            obj.find("[name=" + key + "]").html(value);
                        } else {
                            //看是否是时间格式的
                            if ($oinput.attr("date") == "date" && value != null) {
                                value = value.replace(/-/g, "/").replace(/T/g, " ").replace(/[\.]\d+/, "");
                                obj.find("[name=" + key + "]").val(moment(new Date(value)).format($oinput.attr("format")));
                            } else {
                                //其他
                                if (value == "&nbsp;") {
                                    value = null;
                                }
                                obj.find("[name=" + key + "]").val(value);
                            }
                        }
                        //填充select
                        var $oselect = obj.find("select[name='" + key + "']");
                        //遍历填充 判断是不是select2
                        if ($oselect.hasClass(".select2Forjs") || $oselect.hasClass("select2Forjs")) {
                            $oselect.each(function () {
                                value = "" ? 0 : value;
                                $(this).val(value).trigger("change");
                            });
                        } else {
                            //其他
                            $oselect.each(function () {
                                $(this).val(value);
                            });
                        }
                        //填充Img
                        $img.each(function () {
                            $(this).attr("src", value);
                        });
                    });
            } catch (e) {
                layer.msg("似乎遇到了点儿麻烦，请刷新页面重试");
            }
        },
        error: function (data) {
            layer.msg("似乎遇到了点儿麻烦，请刷新页面重试");
        },
        complete: function () {
            $.loading(false);
        }
    });
}